package cn.lingyangwl.agile.pay.common.constants;

import cn.lingyangwl.agile.pay.constant.IfCodeEnum;
import cn.lingyangwl.agile.pay.common.utils.VelocityUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.velocity.VelocityContext;

import java.util.Arrays;
import java.util.Optional;

/**
 * 支付节点枚举
 * @author shenguangyang
 */
@Getter
@AllArgsConstructor
public enum PayNodeEnum {
    NONE("-1", "未知节点"),
    PAY_INIT("1", "用户${userName}发起支付"),
    PAY_OK("2", "用户${userName}支付成功"),
    PAY_FAIL("3", "用户${userName}支付失败"),
    PAY_CALLBACK_OK("4", "${ifCode}支付回调成功"),
    PAY_CALLBACK_FAIL("5", "${ifCode}支付回调失败"),
    REFUND_INIT("20", "用户${userName}发起退款"),
    REFUND_OK("21", "用户${userName}退款成功"),
    REFUND_FAIL("22", "用户${userName}退款失败"),
    REFUND_CALLBACK_OK("23", "${ifCode}退款回调成功"),
    REFUND_CALLBACK_FAIL("24", "${ifCode}退款回调失败"),

    CLOSE_OK("40", "用户${userName}关闭订单成功"),
    CLOSE_FAIL("41", "用户${userName}关闭订单失败"),
    CLOSE_OK_TIMEOUT("50", "订单超时关闭成功"),
    CLOSE_FAIL_TIMEOUT("51", "订单超时关闭失败"),
    MCH_NOTIFY_FAIL("52", "商户通知失败"),
    MCH_NOTIFY_OK("53", "商户通知成功"),
    ;
    private final String code;
    private final String title;

    public static PayNodeEnum of(String code) {
        return Arrays.stream(values()).filter(e -> e.getCode().equals(code)).findFirst().orElse(PayNodeEnum.NONE);
    }

    public String parse(String userName, IfCodeEnum ifCodeEnum) {
        VelocityContext context = new VelocityContext();
        context.put("ifCode", Optional.ofNullable(ifCodeEnum).map(IfCodeEnum::getDesc).orElse("未知支付接口"));
        context.put("userName", userName);
        return VelocityUtil.generate(context, this.title);
    }
}
